﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Diagnostics;
using System.Windows.Forms.DataVisualization.Charting;

using ClassLibrary;
using Core;

namespace TestProject
{
    public partial class MainWindow : Form
    {
        public Model model;
        public MainWindow()
        {
            InitializeComponent();
            Functions.treeView1 = treeView1;
        }        
        private void tree_update()
        {
            treeView1.BeginUpdate();
            treeView1.Nodes.Clear();
            treeView1.Nodes.Add(model.model_name).Nodes.Add("Tables").Nodes.Add("Gene tables");
            treeView1.Nodes[0].Nodes[0].Nodes.Add("Chromosome tables");
            treeView1.Nodes[0].Nodes[0].Nodes.Add("Phenotype tables");
            treeView1.Nodes[0].Nodes[0].Nodes.Add("Natural selection tables");
            treeView1.Nodes[0].Nodes.Add("Links").Nodes.Add("Chromosome and gene links");
            treeView1.Nodes[0].Nodes[1].Nodes.Add("Genome and phenotype links");
            treeView1.Nodes[0].Nodes[1].Nodes.Add("Natural selection links");
            treeView1.Nodes[0].Nodes[1].Nodes.Add("Crossingover links");
            treeView1.Nodes[0].Nodes[1].Nodes.Add("Reproduction links");
            treeView1.Nodes[0].Nodes.Add("Species");
            foreach (GeneTable gt in model.model_gene_tables.Values)
            {
                treeView1.Nodes[0].Nodes[0].Nodes[0].Nodes.Add(gt.name).Tag = gt;
            }
            foreach (ChromosomeTable chrom_t in model.model_chromosome_tables.Values)
            {
                treeView1.Nodes[0].Nodes[0].Nodes[1].Nodes.Add(chrom_t.name).Tag = chrom_t;
            }
            foreach (PhenotypeTable phen_t in model.model_phenotype_tables.Values)
            {
                treeView1.Nodes[0].Nodes[0].Nodes[2].Nodes.Add(phen_t.name).Tag = phen_t;
            }
            foreach (NaturalSelectionTable natsel_t in model.model_natural_selection_tables.Values)
            {
                treeView1.Nodes[0].Nodes[0].Nodes[3].Nodes.Add(natsel_t.name).Tag = natsel_t;
            }
            foreach (ChromosomeGeneLink chrom_gen_link in model.model_chromosome_gene_links.Values)
            {
                treeView1.Nodes[0].Nodes[1].Nodes[0].Nodes.Add(chrom_gen_link.name).Tag = chrom_gen_link;
            }
            foreach (GenomePhenotypeLink gen_phen_link in model.model_genome_phenotype_links.Values)
            {
                treeView1.Nodes[0].Nodes[1].Nodes[1].Nodes.Add(gen_phen_link.name).Tag = gen_phen_link;
            }
            foreach (NaturalSelectionLink natsel_link in model.model_natural_selection_links.Values)
            {
                treeView1.Nodes[0].Nodes[1].Nodes[2].Nodes.Add(natsel_link.name).Tag = natsel_link;
            }
            foreach (CrossingoverLink cross_link in model.model_crossingover_links.Values)
            {
                treeView1.Nodes[0].Nodes[1].Nodes[3].Nodes.Add(cross_link.name).Tag = cross_link;
            }
            foreach (ReproductionLink reprod_link in model.model_reproduction_links.Values)
            {
                treeView1.Nodes[0].Nodes[1].Nodes[4].Nodes.Add(reprod_link.name).Tag = reprod_link;
            }
            int q = -1;
            foreach (Species species in model.model_species.Values)
            {
                q++;                
                treeView1.Nodes[0].Nodes[2].Nodes.Add(species.name).Tag = species;
                int i = -1;
                foreach (Population pop in species.massive_populations.Values)
                {
                    i++;                    
                    treeView1.Nodes[0].Nodes[2].Nodes[q].Nodes.Add(pop.name).Tag = pop;
                    int j=-1;
                    foreach (Individual indi in pop.massive_individuals)
                    {
                        j++;                                            
                        treeView1.Nodes[0].Nodes[2].Nodes[q].Nodes[i].Nodes.Add(indi.name).Tag = indi;
                        int k=-1;
                        foreach (Chromosome [] chromosome in indi.massive_chromosomes.Values)
                        {
                            k++;                            
                            treeView1.Nodes[0].Nodes[2].Nodes[q].Nodes[i].Nodes[j].Nodes.Add("chromosome pair #" + k);                            
                            for (int g = 0; g < 2; g++)
                            {
                                ChromosomeType chromcat = species.sp_chromosome_table.table[k];                                
                                treeView1.Nodes[0].Nodes[2].Nodes[q].Nodes[i].Nodes[j].Nodes[k].Nodes.Add("chromosome " + chromcat.name).Tag=chromcat;
                                GeneTable gene_table = species.sp_gene_table;
                                foreach (Locus locus in chromosome[g].massive_locus)
                                {                                    
                                    treeView1.Nodes[0].Nodes[2].Nodes[q].Nodes[i].Nodes[j].Nodes[k].Nodes[g].Nodes.Add("Gene " + gene_table.gene_table[locus.gene.allele_type_id].name).Tag = locus.gene;
                                }
                            }
                        }
                    }
                }
            }
            treeView1.EndUpdate();            
        }
        private void model_update()
        {
            model = new Model(model.model_path);
        }

        private void createToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreationForm creation_form = new CreationForm(this);
            creation_form.ShowDialog(this);
            if (model != null)
            {
                tree_update();
                addToolStripMenuItem1.Enabled = true;
            }
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog open_model = new OpenFileDialog();
            open_model.InitialDirectory = Environment.CurrentDirectory + "\\file_input";
            if (open_model.ShowDialog() == DialogResult.OK)
            {
                model = new Model(open_model.FileName);
                tree_update();
                table_layout.Controls.Clear();
                addToolStripMenuItem1.Enabled = true;
            }
        }
        
        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                treeView1.SelectedNode = e.Node;
                if (e.Node.Level == 0)
                    contextMenuStrip1.Show(this.treeView1, e.Location);
                if ((e.Node.Level == 1)&&(e.Node.Text=="Species"))
                {
                    contextMenuStrip3.Items[0].Text = "Add new specie";
                    contextMenuStrip3.Show(this.treeView1, e.Location);
                }
                if ((e.Node.Level == 2) && (e.Node.Parent.Text == "Species"))
                {
                    contextMenuStrip3.Items[0].Text = "Add new population";
                    contextMenuStrip3.Show(this.treeView1, e.Location);
                }
                else if (e.Node.Level == 2)
                {
                    contextMenuStrip3.Items[0].Text = "Add new " + e.Node.Text.Replace("links", "link").Replace("tables", "table").Replace('G', 'g').Replace('C', 'c').Replace('P', 'p').Replace('N', 'n').Replace('R', 'r');
                    contextMenuStrip3.Show(this.treeView1, e.Location);
                }
                if ((e.Node.Level == 3) && (e.Node.Parent.Parent.Text == "Species"))
                {
                    contextMenuStrip3.Items[0].Text = "Add new individual";
                    contextMenuStrip3.Show(this.treeView1, e.Location);
                }
                
            }
        }
        /*
         * Adding existing elemnts would be too complex
        private void existingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            op.InitialDirectory = Environment.CurrentDirectory + "\\file_input";
            if (op.ShowDialog() == DialogResult.OK)
            {
                string path = op.FileName;
                string name = op.SafeFileName;
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = true;
                XmlElement el;
                XmlTextReader reader = new XmlTextReader(op.FileName);
                reader.MoveToContent();
                switch (reader.Name)
                {
                    case "link":
                        switch (reader.GetAttribute("Type"))
                        {
                            case "chromosome_and_gene":
                                if (!File.Exists("file_input\\" + model.model_name + "\\Links\\ChromosomeGeneLinks\\" + name))                                
                                    File.Copy(path, "file_input\\" + model.model_name + "\\Links\\ChromosomeGeneLinks\\" + name);
                                else if (path != Directory.GetParent("file_input\\" + model.model_name + "\\Links\\ChromosomeGeneLinks\\" + name).ToString() + "\\" + name)
                                {
                                    if (MessageBox.Show("File already exists. Replace?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                        File.Copy(path, "file_input\\" + model.model_name + "\\Links\\ChromosomeGeneLinks\\" + name, true);
                                }
                                if (!model.model_chromosome_gene_links.Keys.Contains("file_input\\" + model.model_name + "\\Links\\ChromosomeGeneLinks\\" + name))
                                {
                                    doc.LoadXml(File.ReadAllText(model.model_path));
                                    el = doc.CreateElement("link");
                                    el.SetAttribute("Path", "file_input\\" + model.model_name + "\\Links\\ChromosomeGeneLinks\\" + name);
                                    doc.GetElementsByTagName("links")[0].Attributes[0].Value = (Convert.ToInt32(doc.GetElementsByTagName("links")[0].Attributes[0].Value) + 1).ToString();
                                    doc.DocumentElement.SetAttribute("AmountLinks", (Convert.ToInt32(doc.DocumentElement.GetAttribute("AmountLinks")) + 1).ToString());
                                    doc.GetElementsByTagName("chromosome_and_gene_links")[0].AppendChild(el);
                                    doc.Save(model.model_path);
                                }
                                break;
                            case "genome_and_phenotype":
                                if (!File.Exists("file_input\\" + model.model_name + "\\Links\\GenomePhenotypeLinks\\" + name))                                
                                    File.Copy(path, "file_input\\" + model.model_name + "\\Links\\GenomePhenotypeLinks\\" + name);
                                else if (path != Directory.GetParent("file_input\\" + model.model_name + "\\Links\\GenomePhenotypeLinks\\" + name).ToString() + "\\" + name)
                                {
                                    if (MessageBox.Show("File already exists. Replace?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                        File.Copy(path, "file_input\\" + model.model_name + "\\Links\\GenomePhenotypeLinks\\" + name, true);
                                }
                                if (!model.model_genome_phenotype_links.Keys.Contains("file_input\\" + model.model_name + "\\Links\\GenomePhenotypeLinks\\" + name))
                                {
                                    doc.LoadXml(File.ReadAllText(model.model_path));
                                    el = doc.CreateElement("link");
                                    el.SetAttribute("Path", "file_input\\" + model.model_name + "\\Links\\GenomePhenotypeLinks\\" + name);
                                    doc.GetElementsByTagName("links")[0].Attributes[1].Value = (Convert.ToInt32(doc.GetElementsByTagName("links")[0].Attributes[1].Value) + 1).ToString();
                                    doc.DocumentElement.SetAttribute("AmountLinks", (Convert.ToInt32(doc.DocumentElement.GetAttribute("AmountLinks")) + 1).ToString());
                                    doc.GetElementsByTagName("genome_and_phenotype_links")[0].AppendChild(el);
                                    doc.Save(model.model_path);
                                }
                                break;
                            case "natural_selection":
                                if (!File.Exists("file_input\\" + model.model_name + "\\Links\\NaturalSelectionLinks\\" + name))
                                    File.Copy(path, "file_input\\" + model.model_name + "\\Links\\NaturalSelectionLinks\\" + name);
                                else if (path != Directory.GetParent("file_input\\" + model.model_name + "\\Links\\NaturalSelectionLinks\\" + name).ToString() + "\\" + name)
                                {
                                    if (MessageBox.Show("File already exists. Replace?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                        File.Copy(path, "file_input\\" + model.model_name + "\\Links\\NaturalSelectionLinks\\" + name, true);
                                }
                                if (!model.model_natural_selection_links.Keys.Contains("file_input\\" + model.model_name + "\\Links\\NaturalSelectionLinks\\" + name))
                                {
                                    doc.LoadXml(File.ReadAllText(model.model_path));
                                    el = doc.CreateElement("link");
                                    el.SetAttribute("Id", doc.GetElementsByTagName("natural_selection_links").Count.ToString());
                                    el.SetAttribute("Path", "file_input\\" + model.model_name + "\\Links\\NaturalSelectionLinks\\" + name);
                                    doc.GetElementsByTagName("links")[0].Attributes[2].Value = (Convert.ToInt32(doc.GetElementsByTagName("links")[0].Attributes[2].Value) + 1).ToString();
                                    doc.DocumentElement.SetAttribute("AmountLinks", (Convert.ToInt32(doc.DocumentElement.GetAttribute("AmountLinks")) + 1).ToString());
                                    doc.GetElementsByTagName("natural_selection_links")[0].AppendChild(el);
                                    doc.Save(model.model_path);
                                }
                                break;
                            case "crossingover":
                                if (!File.Exists("file_input\\" + model.model_name + "\\Links\\CrossingoverLinks\\" + name))                                
                                    File.Copy(path, "file_input\\" + model.model_name + "\\Links\\CrossingoverLinks\\" + name);                        
                                else if (path != Directory.GetParent("file_input\\" + model.model_name + "\\Links\\CrossingoverLinks\\" + name).ToString() + "\\" + name)
                                {
                                    if (MessageBox.Show("File already exists. Replace?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                        File.Copy(path, "file_input\\" + model.model_name + "\\Links\\CrossingoverLinks\\" + name, true);
                                }
                                if (!model.model_crossingover_links.Keys.Contains("file_input\\" + model.model_name + "\\Links\\CrossingoverLinks\\" + name))
                                {
                                    doc.LoadXml(File.ReadAllText(model.model_path));
                                    el = doc.CreateElement("link");
                                    el.SetAttribute("Path", "file_input\\" + model.model_name + "\\Links\\CrossingoverLinks\\" + name);
                                    doc.GetElementsByTagName("links")[0].Attributes[3].Value = (Convert.ToInt32(doc.GetElementsByTagName("links")[0].Attributes[3].Value) + 1).ToString();
                                    doc.DocumentElement.SetAttribute("AmountLinks", (Convert.ToInt32(doc.DocumentElement.GetAttribute("AmountLinks")) + 1).ToString());
                                    doc.GetElementsByTagName("genome_and_phenotype_links")[0].AppendChild(el);
                                    doc.Save(model.model_path);
                                }
                                break;
                        }
                        break;
                    case "gene_table":
                        if (!File.Exists("file_input\\" + model.model_name + "\\Tables\\GeneTables\\" + name))
                            File.Copy(path, "file_input\\" + model.model_name + "\\Tables\\GeneTables\\" + name);
                        else if (path != Directory.GetParent("file_input\\" + model.model_name + "\\Tables\\GeneTables\\" + name).ToString() + "\\" + name)
                        {
                            if (MessageBox.Show("File already exists. Replace?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                File.Copy(path, "file_input\\" + model.model_name + "\\Tables\\GeneTables\\" + name, true);
                        }
                        if (!model.model_gene_tables.Keys.Contains("file_input\\" + model.model_name + "\\Tables\\GeneTables\\" + name))
                        {
                            doc.LoadXml(File.ReadAllText(model.model_path));
                            el = doc.CreateElement("table");
                            el.SetAttribute("Path", "file_input\\" + model.model_name + "\\Tables\\GeneTables\\" + name);
                            doc.GetElementsByTagName("tables")[0].Attributes[0].Value = (Convert.ToInt32(doc.GetElementsByTagName("tables")[0].Attributes[0].Value) + 1).ToString();
                            doc.DocumentElement.SetAttribute("AmountTables", (Convert.ToInt32(doc.DocumentElement.GetAttribute("AmountTables")) + 1).ToString());
                            doc.GetElementsByTagName("gene_tables")[0].AppendChild(el);
                            doc.Save(model.model_path);
                        }
                        break;
                    case "chromosome_table":
                        if (!File.Exists("file_input\\" + model.model_name + "\\Tables\\ChromosomeTables\\" + name))
                            File.Copy(path, "file_input\\" + model.model_name + "\\Tables\\ChromosomeTables\\" + name);
                        else if (path != Directory.GetParent("file_input\\" + model.model_name + "\\Tables\\ChromosomeTables\\" + name).ToString() + "\\" + name)
                        {
                            if (MessageBox.Show("File already exists. Replace?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                File.Copy(path, "file_input\\" + model.model_name + "\\Tables\\ChromosomeTables\\" + name, true);
                        }
                        if (!model.model_chromosome_tables.Keys.Contains("file_input\\" + model.model_name + "\\Tables\\ChromosomeTables\\" + name))
                        {
                            doc.LoadXml(File.ReadAllText(model.model_path));
                            el = doc.CreateElement("table");
                            el.SetAttribute("Path", "file_input\\" + model.model_name + "\\Tables\\ChromosomeTables\\" + name);
                            doc.GetElementsByTagName("tables")[0].Attributes[1].Value = (Convert.ToInt32(doc.GetElementsByTagName("tables")[0].Attributes[1].Value) + 1).ToString();
                            doc.DocumentElement.SetAttribute("AmountTables", (Convert.ToInt32(doc.DocumentElement.GetAttribute("AmountTables")) + 1).ToString());
                            doc.GetElementsByTagName("chromosome_tables")[0].AppendChild(el);
                            doc.Save(model.model_path);
                        }
                        break;
                    case "table":
                        if (!File.Exists("file_input\\" + model.model_name + "\\Tables\\NaturalSelectionTables\\" + name))
                            File.Copy(path, "file_input\\" + model.model_name + "\\Tables\\NaturalSelectionTables\\" + name);
                        else if (path != Directory.GetParent("file_input\\" + model.model_name + "\\Tables\\NaturalSelectionTables\\" + name).ToString() + "\\" + name)
                        {
                            if (MessageBox.Show("File already exists. Replace?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                File.Copy(path, "file_input\\" + model.model_name + "\\Tables\\NaturalSelectionTables\\" + name, true);
                        }
                        if (!model.model_chromosome_tables.Keys.Contains("file_input\\" + model.model_name + "\\Tables\\NaturalSelectionTables\\" + name))
                        {
                            doc.LoadXml(File.ReadAllText(model.model_path));
                            el = doc.CreateElement("table");
                            el.SetAttribute("Path", "file_input\\" + model.model_name + "\\Tables\\NaturalSelectionTables\\" + name);
                            doc.GetElementsByTagName("tables")[0].Attributes[3].Value = (Convert.ToInt32(doc.GetElementsByTagName("tables")[0].Attributes[3].Value) + 1).ToString();
                            doc.DocumentElement.SetAttribute("AmountTables", (Convert.ToInt32(doc.DocumentElement.GetAttribute("AmountTables")) + 1).ToString());
                            doc.GetElementsByTagName("natural_selection_tables")[0].AppendChild(el);
                            doc.Save(model.model_path);
                        }
                        break;
                    case "phenotype_table":
                        if (!File.Exists("file_input\\" + model.model_name + "\\Tables\\PhenotypeTables\\" + name))
                            File.Copy(path, "file_input\\" + model.model_name + "\\Tables\\PhenotypeTables\\" + name);
                        else if (path != Directory.GetParent("file_input\\" + model.model_name + "\\Tables\\PhenotypeTables\\" + name).ToString() + "\\" + name)
                        {
                            if (MessageBox.Show("File already exists. Replace?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                File.Copy(path, "file_input\\" + model.model_name + "\\Tables\\PhenotypeTables\\" + name, true);
                        }
                        if (!model.model_chromosome_tables.Keys.Contains("file_input\\" + model.model_name + "\\Tables\\PhenotypeTables\\" + name))
                        {
                            doc.LoadXml(File.ReadAllText(model.model_path));
                            el = doc.CreateElement("table");
                            el.SetAttribute("Path", "file_input\\" + model.model_name + "\\Tables\\PhenotypeTables\\" + name);
                            doc.GetElementsByTagName("tables")[0].Attributes[2].Value = (Convert.ToInt32(doc.GetElementsByTagName("tables")[0].Attributes[2].Value) + 1).ToString();
                            doc.DocumentElement.SetAttribute("AmountTables", (Convert.ToInt32(doc.DocumentElement.GetAttribute("AmountTables")) + 1).ToString());
                            doc.GetElementsByTagName("phenotype_tables")[0].AppendChild(el);
                            doc.Save(model.model_path);
                        }
                        break;
                       
                    case "species":
                        if (!Directory.Exists("file_input\\" + model.model_name + "\\Species\\" + reader.GetAttribute("Name")))
                        {
                            Directory.CreateDirectory("file_input\\" + model.model_name + "\\Species\\" + reader.GetAttribute("Name"));
                            File.Copy(path, "file_input\\" + model.model_name + "\\Species\\" + reader.GetAttribute("Name") + "\\" + name);
                        }
                        else
                        {
                            if (MessageBox.Show("File already exists. Replace?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                Directory.Delete("file_input\\" + model.model_name + "\\Species\\" + reader.GetAttribute("Name"));
                                Process proc = Process.Start("cmd.exe", "/C xcopy " + path + " " + "file_input\\" + model.model_name + "\\Species\\" + reader.GetAttribute("Name") + " /e /i /h /y");
                                proc.WaitForExit();
                            }
                        }
                        doc.LoadXml(File.ReadAllText(model.model_path));
                        el = doc.CreateElement("sp");
                        el.SetAttribute("Path", Directory.GetParent("file_input\\" + model.model_name + "\\Species\\" + reader.GetAttribute("Name") + "\\" + name).ToString() + "\\" + name);
                        doc.GetElementsByTagName("tables")[0].Attributes[1].Value = (Convert.ToInt32(doc.GetElementsByTagName("tables")[0].Attributes[1].Value) + 1).ToString();
                        doc.DocumentElement.SetAttribute("AmountTables", (Convert.ToInt32(doc.DocumentElement.GetAttribute("AmountTables")) + 1).ToString());
                        doc.GetElementsByTagName("chromosome_tables")[0].AppendChild(el);
                        doc.Save(model.model_path);
                        break;
                }
                reader.Close();
            }
            model_update();
            tree_update();
        }   
        */
        private void geneTableToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            NewGeneTable new_gene_table = new NewGeneTable(model);
            new_gene_table.ShowDialog(this);
            model_update();
        }

        private void chromosomeTableToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewChromosomeTable new_chromosome_table = new NewChromosomeTable(model);
            new_chromosome_table.ShowDialog(this);
            model_update();
        }

        private void removeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            remove_item();
        }
        private string remove_item()
        {
            string s = null;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(File.ReadAllText(model.model_path));
            XmlTextReader reader;
            if (treeView1.SelectedNode.Parent.Text == "Links")
            {
                doc.GetElementsByTagName("links")[0].Attributes[0].Value = (Convert.ToInt32(doc.GetElementsByTagName("links")[0].Attributes[0].Value) - 1).ToString();
                doc.DocumentElement.SetAttribute("AmountLinks", (Convert.ToInt32(doc.DocumentElement.GetAttribute("AmountLinks")) - 1).ToString());
                foreach (XmlElement x in doc.GetElementsByTagName("link"))
                {
                    s = x.Attributes[0].Value;
                    reader = new XmlTextReader(s);
                    reader.MoveToContent();
                    if (reader.GetAttribute("Name") == treeView1.SelectedNode.Text)
                    {
                        x.ParentNode.RemoveChild(x);
                        reader.Close();
                        break;
                    }
                }
            }
            if (treeView1.SelectedNode.Parent.Text == "Gene tables")
            {
                doc.GetElementsByTagName("tables")[0].Attributes[0].Value = (Convert.ToInt32(doc.GetElementsByTagName("tables")[0].Attributes[0].Value) - 1).ToString();
                doc.DocumentElement.SetAttribute("AmountTables", (Convert.ToInt32(doc.DocumentElement.GetAttribute("AmountTables")) - 1).ToString());
                foreach (XmlElement x in doc.GetElementsByTagName("gene_tables")[0].ChildNodes)
                {
                    s = x.Attributes[0].Value;
                    reader = new XmlTextReader(s);
                    reader.MoveToContent();
                    if (reader.GetAttribute("Name") == treeView1.SelectedNode.Text)
                    {
                        reader.Close();
                        x.ParentNode.RemoveChild(x);
                        break;
                    }
                }
            }
            if (treeView1.SelectedNode.Parent.Text == "Chromosome tables")
            {
                doc.GetElementsByTagName("tables")[0].Attributes[1].Value = (Convert.ToInt32(doc.GetElementsByTagName("tables")[0].Attributes[1].Value) - 1).ToString();
                doc.DocumentElement.SetAttribute("AmountTables", (Convert.ToInt32(doc.DocumentElement.GetAttribute("AmountTables")) - 1).ToString());
                foreach (XmlElement x in doc.GetElementsByTagName("chromosome_tables")[0].ChildNodes)
                {
                    s = x.Attributes[0].Value;
                    reader = new XmlTextReader(x.Attributes[0].Value);
                    reader.MoveToContent();
                    if (reader.GetAttribute("Name") == treeView1.SelectedNode.Text)
                    {
                        reader.Close();
                        x.ParentNode.RemoveChild(x);
                        break;
                    }
                }
            }
            treeView1.SelectedNode.Remove();
            doc.Save(model.model_path);
            model_update();
            return s;
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            File.Delete(remove_item());
        }

        private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            PropControls props;
            table_layout.Controls.Clear();
            table_layout.RowStyles.Clear();
            table_layout.ColumnStyles.Clear();
            table_layout.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            table_layout.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            table_layout.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            table_layout.RowCount = 0;
            table_layout.ColumnCount = 3;
            object tag = e.Node.Tag;
            edit_butt.Hide();
            if (e.Node.Level == 0)
            {
                props = new PropControls(4);
                props.labels[0].Text = "Name";
                props.boxes[0].Text = model.model_name;
                props.labels[1].Text = "Amount of tables";
                props.boxes[1].Text = (model.model_chromosome_tables.Count + model.model_gene_tables.Count).ToString();
                props.boxes[1].Size = new System.Drawing.Size(30, 23);
                props.labels[2].Text = "Amount of links";
                props.boxes[2].Text = model.model_chromosome_gene_links.Count.ToString();
                props.boxes[2].Size = new System.Drawing.Size(30, 23);
                props.labels[3].Text = "Amount of species";
                props.boxes[3].Text = model.model_species.Count.ToString();
                props.boxes[3].Size = new System.Drawing.Size(30, 23);
                props.add_to_table_layout_panel(table_layout);
            }
            else if (e.Node.Level == 1)
            {
                switch (e.Node.Text)
                {
                    case "Tables":
                        props = new PropControls(3);
                        props.labels[0].Text = "Amount of gene tables";
                        props.labels[1].Text = "Amount of chromosome tables";
                        props.labels[2].Text = "Amount of phenotype tables";
                        props.boxes[0].Text = model.model_gene_tables.Count.ToString();
                        props.boxes[1].Text = model.model_chromosome_tables.Count.ToString();
                        props.boxes[2].Text = model.model_phenotype_tables.Count.ToString();
                        props.boxes[0].Size = new System.Drawing.Size(30, 23);
                props.boxes[1].Size = new System.Drawing.Size(30, 23);
                props.boxes[2].Size = new System.Drawing.Size(30, 23);
                        props.add_to_table_layout_panel(table_layout);
                        break;
                    case "Links":
                        props = new PropControls(4);
                        props.labels[0].Text = "Amount of chromosome and gene links";
                        props.labels[1].Text = "Amount of genome-phenotype links";
                        props.labels[2].Text = "Amount of natural selection links";
                        props.labels[3].Text = "Amount of crossingover links";
                        props.boxes[0].Text = model.model_chromosome_gene_links.Count.ToString();
                        props.boxes[1].Text = model.model_genome_phenotype_links.Count.ToString();
                        props.boxes[2].Text = model.model_natural_selection_links.Count.ToString();
                        props.boxes[3].Text = model.model_crossingover_links.Count.ToString();
                        props.boxes[0].Size = new System.Drawing.Size(30, 23);
                props.boxes[1].Size = new System.Drawing.Size(30, 23);
                props.boxes[2].Size = new System.Drawing.Size(30, 23);
                props.boxes[3].Size = new System.Drawing.Size(30, 23);
                        props.add_to_table_layout_panel(table_layout);
                        break;
                    case "Species":
                        props = new PropControls(1);
                        props.labels[0].Text = "Amount species";
                        props.boxes[0].Text = model.model_species.Count.ToString();
                            props.boxes[0].Size = new System.Drawing.Size(30, 23);
                        props.add_to_table_layout_panel(table_layout);
                        break;
                }
            }
            else if (e.Node.Parent.Text == "Species")
            {
                Species specie = (Species)tag;
                props = new PropControls(2);
                props.labels[0].Text = "Name";
                props.labels[1].Text = "Amount of populations";
                props.boxes[0].Text = specie.name;
                props.boxes[1].Text = specie.amount_populations.ToString();
                    props.boxes[1].Size = new System.Drawing.Size(30, 23);
                props.add_to_table_layout_panel(table_layout);                

            }
            else if (e.Node.Level == 3)
            {
                Label l1 = new Label();
                Label l2 = new Label();
                ComboBox cb1 = new ComboBox();
                TextBox tb = new TextBox();
                switch (e.Node.Parent.Text)
                {
                    case "Chromosome and gene links":
                        ChromosomeGeneLink chrom_gene_link = (ChromosomeGeneLink)tag;
                        props = new PropControls("chrom_gene");
                        props.labels[0].Text = "Name";
                        props.boxes[0].Text = chrom_gene_link.name;
                        props.labels[1].Text = "Chromosome table";
                        props.boxes[1].Text = model.model_chromosome_tables[chrom_gene_link.path_to_chromosome_table].name;
                        props.boxes[1].Tag = model.model_chromosome_tables[chrom_gene_link.path_to_chromosome_table];
                        props.labels[2].Text = "Gene table";
                        props.boxes[2].Text = model.model_gene_tables[chrom_gene_link.path_to_gene_table].name;
                        props.boxes[2].Tag = model.model_gene_tables[chrom_gene_link.path_to_gene_table];
                        props.labels[3].Text = "Chromosome pairs amount";
                        if (model.model_chromosome_tables[chrom_gene_link.path_to_chromosome_table].table != null)
                        {
                            foreach (ChromosomeType chromt in model.model_chromosome_tables[chrom_gene_link.path_to_chromosome_table].table)
                            {
                                props.cbox1.Items.Add(chromt.name);
                            }
                        }
                        props.boxes[3].Text = chrom_gene_link.chromosome_pairs_amount.ToString();
                        props.cbox1.SelectedIndexChanged += new EventHandler(cbox1_select_change);
                        props.cbox2.SelectedIndexChanged += new EventHandler(cbox2_select_change);
                        props.cbox2.Tag = tag;
                        foreach (GeneType g in model.model_gene_tables[chrom_gene_link.path_to_gene_table].gene_table)
                        {
                            props.cbox3.Items.Add(g.name);
                        }
                        props.add_to_table_layout_panel(table_layout);
                        Button b2 = new Button();
                        b2.Text = "Change";
                        b2.Click += new EventHandler(change_click);
                        b2.Hide();
                        table_layout.Controls.Add(b2, 2, 6);
                        break;
                    case "Genome and phenotype links":
                        GenomePhenotypeLink gen_phen_link = (GenomePhenotypeLink)tag;
                        props = new PropControls(4);
                        props.labels[0].Text = "Name";
                        props.boxes[0].Text = gen_phen_link.name;
                        props.labels[1].Text = "Phenotype table";
                        props.boxes[1].Text = model.model_phenotype_tables[gen_phen_link.path_to_phenotype_table].name;
                        props.boxes[1].Tag = model.model_phenotype_tables[gen_phen_link.path_to_phenotype_table];
                        props.labels[2].Text = "Gene table";
                        props.boxes[2].Tag = model.model_gene_tables[gen_phen_link.path_to_gene_table];
                        props.boxes[2].Text = model.model_gene_tables[gen_phen_link.path_to_gene_table].name;
                        props.labels[3].Text = "Characteristics amount";
                        props.boxes[3].Text = gen_phen_link.characteristics_amount.ToString();
                        props.add_to_table_layout_panel(table_layout);
                        Label char_l = new Label();
                        char_l.Text = "Characteristic";
                        char_l.Anchor = AnchorStyles.Left;
                        char_l.AutoSize = true;
                        ComboBox char_cb = new ComboBox();
                        foreach (CharacteristicDescription desc in model.model_phenotype_tables[gen_phen_link.path_to_phenotype_table].characteristic_table.Values)
                        {
                            char_cb.Items.Add(desc.name);
                        }
                        char_cb.SelectedIndexChanged += new EventHandler(charac1_changed);
                        Label val_l = new Label();
                        val_l.Text = "Value";
                        val_l.AutoSize = true;
                        val_l.Anchor = AnchorStyles.Left;
                        ComboBox val_cb = new ComboBox();
                        val_cb.SelectedIndexChanged += new EventHandler(value_changed);
                        table_layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                        table_layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                        table_layout.Controls.Add(char_l, 0, table_layout.RowCount);
                        table_layout.Controls.Add(char_cb, 1, table_layout.RowCount);
                        table_layout.Controls.Add(val_l, 0, table_layout.RowCount+1);
                        table_layout.Controls.Add(val_cb, 1, table_layout.RowCount+1);
                        table_layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                        TableLayoutPanel table = new TableLayoutPanel();
                        table_layout.Controls.Add(table, 0, 6);
                        table_layout.SetColumnSpan(table, 2);
                        table.AutoSize = true;
                        table.AutoSizeMode = AutoSizeMode.GrowAndShrink;
                        Button bb = new Button();
                        bb.Text = "Change";
                        bb.Hide();
                        bb.Anchor = AnchorStyles.Left;
                        bb.Click += new EventHandler(change_click);
                        table_layout.Controls.Add(bb, 2, table_layout.RowCount+2);
                        table_layout.RowCount += 3;
                        break;
                    case "Natural selection links":
                        ClassLibrary.NaturalSelectionLink natselect_link = (NaturalSelectionLink)tag;
                        props = new PropControls(3);
                        props.labels[0].Text = "Name";
                        props.boxes[0].Text = natselect_link.name;
                        props.labels[1].Text = "Phenotype table";
                        props.boxes[1].Text = model.model_phenotype_tables[natselect_link.path_to_phenotype_table].name;
                        props.boxes[1].Tag = model.model_phenotype_tables[natselect_link.path_to_phenotype_table];
                        props.labels[2].Text = "Characteristics amount";
                        props.boxes[2].Text = natselect_link.characteristic_amount.ToString();
                        List<Label[]> listl = new List<Label[]>();
                        List<ComboBox[]> listc = new List<ComboBox[]>();
                        props.add_to_table_layout_panel(table_layout);
                        for (int i = 0; i < natselect_link.characteristic_amount; i++)
                        {
                            listl.Add(new Label[2]);
                            listc.Add(new ComboBox[2]);
                            for (int j = 0; j < 2; j++)
                            {
                                listl[i][j] = new Label();
                                listl[i][j].Anchor = AnchorStyles.Left;
                                listl[i][j].AutoSize = true;
                                listc[i][j] = new ComboBox();
                                if (i > 0)
                                {
                                    listl[i][j].Hide();
                                    listc[i][j].Hide();
                                }
                            }
                            listl[i][0].Text = "Characteristic";
                            listl[i][1].Text = "Value";
                            listc[i][0].SelectedIndexChanged += new EventHandler(charac_changed);
                            listc[i][1].SelectedIndexChanged += new EventHandler(value_changed);
                            foreach (CharacteristicDescription charc in model.model_phenotype_tables[natselect_link.path_to_phenotype_table].characteristic_table.Values)
                            {
                                listc[i][0].Items.Add(charc.name);
                            }
                            for (int k = 0; k < 2; k++)
                            {
                                table_layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                                table_layout.Controls.Add(listl[i][k], 0, 3 + 2 * i + k);
                                table_layout.Controls.Add(listc[i][k], 1, 3 + 2 * i + k);
                                table_layout.RowCount++;
                            }
                        }
                        Label l = new Label();
                        ComboBox cb = new ComboBox();
                        l.Text = "Event";
                        l.Anchor = AnchorStyles.Left;
                        l.AutoSize = true;
                        l.Hide();
                        cb.Items.Add("Having Progency");
                        cb.Items.Add("No Having Progency");
                        cb.Hide();
                        cb.Enabled = false;
                        table_layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                        table_layout.Controls.Add(l, 0, table_layout.RowCount);
                        table_layout.Controls.Add(cb, 1, table_layout.RowCount);
                        table_layout.RowCount++;
                        Button b4 = new Button();
                        b4.Click += new EventHandler(change_click);
                        b4.Text = "Change";
                        b4.Hide();
                        table_layout.Controls.Add(b4, 2, table_layout.RowCount - 1);
                        break;
                    case "Crossingover links":
                        CrossingoverLink cross_link = (CrossingoverLink)tag;
                        props = new PropControls("crossingover");
                        props.labels[0].Text = "Name";
                        props.boxes[0].Text = cross_link.name;
                        props.labels[1].Text = "Chromosome table";
                        props.boxes[1].Text = model.model_chromosome_tables[cross_link.path_to_chromosome_table].name;
                        props.boxes[1].Tag = model.model_chromosome_tables[cross_link.path_to_chromosome_table];
                        props.labels[2].Text = "Chromosome pairs amount";
                        props.boxes[2].Text = cross_link.chromosome_pairs_amount.ToString();
                        foreach (ChromosomeType chromt in model.model_chromosome_tables[cross_link.path_to_chromosome_table].table)
                        {
                            props.cbox1.Items.Add(chromt.name);
                        }
                        props.cbox1.SelectedIndexChanged += new EventHandler(cbox1_select_change);
                        props.cbox2.SelectedIndexChanged += new EventHandler(cbox2_select_change);
                        props.cbox2.Tag = tag;
                        props.add_to_table_layout_panel(table_layout);
                        Button cross_change = new Button();
                        cross_change.Text = "Change";
                        cross_change.Click += new EventHandler(change_click);
                        cross_change.Hide();
                        table_layout.Controls.Add(cross_change, 2, table_layout.RowCount-1);
                        break;
                    case "Reproduction links":
                        ReproductionLink reprod_link = (ReproductionLink)tag;
                        props = new PropControls(4);
                        props.labels[0].Text = "Name";
                        props.boxes[0].Text = reprod_link.name;
                        props.labels[1].Text = "Phenotype table";
                        props.boxes[1].Text = model.model_phenotype_tables[reprod_link.path_to_phenotype_table].name;
                        props.boxes[1].Tag = model.model_phenotype_tables[reprod_link.path_to_phenotype_table];
                        props.labels[2].Text = "Natural selection link";
                        props.boxes[2].Text = model.model_natural_selection_links[reprod_link.path_to_natsel_link].name;
                        props.boxes[2].Tag = model.model_natural_selection_links[reprod_link.path_to_natsel_link];
                        props.labels[3].Text = "Characteristics amount";
                        props.boxes[3].Text = reprod_link.characteristic_amount.ToString();
                        List<Label[]> replistl = new List<Label[]>();
                        List<ComboBox[]> replistc = new List<ComboBox[]>();
                        props.add_to_table_layout_panel(table_layout);
                        for (int i = 0; i < reprod_link.characteristic_amount; i++)
                        {
                            replistl.Add(new Label[2]);
                            replistc.Add(new ComboBox[2]);
                            for (int j = 0; j < 2; j++)
                            {
                                replistl[i][j] = new Label();
                                replistl[i][j].Anchor = AnchorStyles.Left;
                                replistl[i][j].AutoSize = true;
                                replistc[i][j] = new ComboBox();
                                if (i > 0)
                                {
                                    replistl[i][j].Hide();
                                    replistc[i][j].Hide();
                                }
                            }
                            replistl[i][0].Text = "Characteristic";
                            replistl[i][1].Text = "Value";
                            replistc[i][0].SelectedIndexChanged += new EventHandler(charac_changed);
                            replistc[i][1].SelectedIndexChanged += new EventHandler(value_changed);
                            foreach (CharacteristicDescription charc in model.model_phenotype_tables[reprod_link.path_to_phenotype_table].characteristic_table.Values)
                            {
                                replistc[i][0].Items.Add(charc.name);
                            }
                            for (int k = 0; k < 2; k++)
                            {
                                table_layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                                table_layout.Controls.Add(replistl[i][k], 0, 4 + 2 * i + k);
                                table_layout.Controls.Add(replistc[i][k], 1, 4 + 2 * i + k);
                                table_layout.RowCount++;
                            }
                        }
                        Label repl = new Label();
                        NumericUpDown nud = new NumericUpDown();
                        repl.Text = "Number of children";
                        repl.AutoSize = true;
                        repl.Anchor = AnchorStyles.Left;
                        repl.Hide();
                        nud.Hide();
                        nud.Enabled = false;
                        table_layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                        table_layout.Controls.Add(repl, 0, table_layout.RowCount);
                        table_layout.Controls.Add(nud, 1, table_layout.RowCount);
                        Button repb4 = new Button();
                        repb4.Click += new EventHandler(change_click);
                        repb4.Text = "Change";
                        repb4.Hide();
                        table_layout.Controls.Add(repb4, 2, table_layout.RowCount);
                        table_layout.RowCount++;
                        break;
                    case "Gene tables":
                        edit_butt.Show();
                        GeneTable gen_table = (GeneTable)tag;
                        props = new PropControls(2);
                        props.labels[0].Text = "Name";
                        props.labels[1].Text = "Gene categories amount";
                        props.boxes[0].Text = gen_table.name;
                        props.boxes[1].Text = gen_table.gene_types_amount.ToString();
                        props.add_to_table_layout_panel(table_layout);
                        l1.Text = "Gene";
                        l1.Anchor = AnchorStyles.Left;
                        l1.AutoSize = true;
                        l2.Text = "Amount alleles";
                        l2.Anchor = AnchorStyles.Left;
                        l2.AutoSize = true;
                        if (gen_table.gene_table != null)
                        {
                            foreach (GeneType g in gen_table.gene_table)
                            {
                                cb1.Items.Add(g.name);
                            }
                        }
                        cb1.SelectedIndexChanged += new EventHandler(gene_changed);
                        table_layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                        table_layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                        table_layout.Controls.Add(l1, 0, 2);
                        table_layout.Controls.Add(cb1, 1, 2);
                        table_layout.Controls.Add(l2, 0, 3);
                        table_layout.Controls.Add(tb, 1, 3);
                        table_layout.RowCount += 2;
                        break;
                    case "Chromosome tables":
                        edit_butt.Show();
                        ChromosomeTable ch_table = (ChromosomeTable)tag;
                        props = new PropControls(2);
                        props.labels[0].Text = "Name";
                        props.labels[1].Text = "Chromosome pairs amount";
                        props.boxes[0].Text = ch_table.name;
                        props.boxes[1].Text = ch_table.chromosome_pairs_amount.ToString();
                        props.add_to_table_layout_panel(table_layout);
                        l1.Text = "Chromosome";
                        l1.Anchor = AnchorStyles.Left;
                        l1.AutoSize = true;
                        l2.Text = "Amount locuses";
                        l2.Anchor = AnchorStyles.Left;
                        l2.AutoSize = true;
                        if (ch_table.table != null)
                        {
                            foreach (ChromosomeType ch in ch_table.table)
                            {
                                cb1.Items.Add(ch.name);
                            }
                        }
                        cb1.SelectedIndexChanged += new EventHandler(chrom_changed);
                        table_layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                        table_layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                        table_layout.Controls.Add(l1, 0, 2);
                        table_layout.Controls.Add(cb1, 1, 2);
                        table_layout.Controls.Add(l2, 0, 3);
                        table_layout.Controls.Add(tb, 1, 3);
                        table_layout.RowCount += 2;
                        break;
                    case "Phenotype tables":
                        edit_butt.Show();
                        PhenotypeTable phen_table = (PhenotypeTable)tag;
                        props = new PropControls(2);
                        props.labels[0].Text = "Name";
                        props.labels[1].Text = "Characteristics amount";
                        props.boxes[0].Text = phen_table.name;
                        props.boxes[1].Text = phen_table.characteristics_amount.ToString();
                        props.add_to_table_layout_panel(table_layout);
                        l1.Text = "Characteristic";
                        l1.Anchor = AnchorStyles.Left;
                        l1.AutoSize = true;
                        l2.Text = "Max degree";
                        l2.Anchor = AnchorStyles.Left;
                        l2.AutoSize = true;
                        foreach (CharacteristicDescription charac in phen_table.characteristic_table.Values)
                        {
                            cb1.Items.Add(charac.name);
                        }
                        cb1.SelectedIndexChanged += new EventHandler(charac1_changed);
                        table_layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                        table_layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                        table_layout.Controls.Add(l1, 0, 2);
                        table_layout.Controls.Add(cb1, 1, 2);
                        table_layout.Controls.Add(l2, 0, 3);
                        table_layout.Controls.Add(tb, 1, 3);
                        table_layout.RowCount += 2;
                        break;
                    case "Natural selection tables":
                        edit_butt.Show();
                        NaturalSelectionTable nat_sel_table = (NaturalSelectionTable)tag;
                        props = new PropControls(5);
                        props.labels[0].Text = "Name";
                        props.labels[1].Text = "Phenotype table";
                        props.labels[2].Text = "Default natural\nselection link";
                        props.labels[3].Text = "Default reproduction link";
                        props.labels[4].Text = "Variants amount";
                        props.boxes[0].Text = nat_sel_table.name;
                        props.boxes[1].Text = model.model_phenotype_tables[nat_sel_table.path_to_phenotype_table].name;
                        props.boxes[2].Text = model.model_natural_selection_links[nat_sel_table.path_to_default_natural_selection_link].name;
                        props.boxes[3].Text = model.model_reproduction_links[nat_sel_table.path_to_default_reproduction_link].name;
                        props.boxes[4].Text = nat_sel_table.natural_selection_variants_amount.ToString();
                        props.add_to_table_layout_panel(table_layout);
                        break;
                    default:
                        Population pop = (Population)tag;
                        props = new PropControls(2);
                        props.labels[0].Text = "Name";
                        props.labels[1].Text = "Amount of individuals";
                        props.boxes[0].Text = pop.name;
                        props.boxes[1].Text = pop.amount_individuals.ToString();
                        props.add_to_table_layout_panel(table_layout);
                        break;
                }
            }
            else if (e.Node.Level == 4)
            {
                Individual indi = (Individual)tag;
                props = new PropControls(2);
                props.labels[0].Text = "Name";
                props.labels[1].Text = "Chromosome pairs amount";
                props.boxes[0].Text = indi.name;
                props.boxes[1].Text = indi.amount_chromosome_pairs.ToString();
                props.add_to_table_layout_panel(table_layout);
            }
            else if (e.Node.Level == 7)
            {
                Gene gen = (Gene)tag;
                props = new PropControls(1);
                props.labels[0].Text = "Name";
                props.boxes[0].Text = e.Node.Text.Split(' ').Last();
                Label g_l = new Label();
                g_l.Anchor = AnchorStyles.Left;
                g_l.AutoSize = true;
                g_l.Text = "Allele's ID";
                ComboBox g_cb = new ComboBox();
                Species s = (Species)e.Node.Parent.Parent.Parent.Parent.Parent.Tag;
                foreach (GeneType g in s.sp_gene_table.gene_table)
                {
                    if (props.boxes[0].Text == g.name)
                    {
                        for (int i = 0; i < g.amount_alelles; i++)
                        {
                            g_cb.Items.Add(i);
                        }
                        break;
                    }
                }
                g_cb.SelectedIndex = gen.allele;
                g_cb.Enabled = false;
                props.add_to_table_layout_panel(table_layout);
                table_layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                table_layout.Controls.Add(g_l, 0, 1);
                table_layout.Controls.Add(g_cb, 1, 1);
                Button g_b = new Button();
                g_b.Text = "Change";
                g_b.Click += new EventHandler(change_click);
                table_layout.Controls.Add(g_b, 2, 1);
                table_layout.RowCount++;                
            }
            if (((e.Node.Level != 1)&&(e.Node.Level!=2) && (e.Node.Level < 5)) || (e.Node.Parent.Text == "Species"))
            {
                Button rename_butt = new Button();
                rename_butt.Text = "Rename";
                rename_butt.Click += new EventHandler(rename_click);
                table_layout.Controls.Add(rename_butt, 2, 0);
            }
        }
        private void charac1_changed(object sender, EventArgs e)
        {
            ComboBox cb = (ComboBox)sender;
            CharacteristicDescription chardesc = null;
            PhenotypeTable phentable;
            switch (treeView1.SelectedNode.Parent.Text)
            {
                case "Phenotype tables":                    
                    TextBox tb = (TextBox)table_layout.Controls[7];
                    phentable = (PhenotypeTable)treeView1.SelectedNode.Tag;
                    foreach (CharacteristicDescription charac in phentable.characteristic_table.Values)
                    {
                        if ((string)cb.SelectedItem == charac.name)
                            chardesc = charac;
                    }
                    tb.Text = chardesc.max_degree.ToString();
                    break;
                case "Genome and phenotype links":
                    ComboBox val_box = (ComboBox)table_layout.Controls[11];
                    val_box.Items.Clear();
                    phentable = (PhenotypeTable)table_layout.Controls[3].Tag;
                    foreach (CharacteristicDescription charac in phentable.characteristic_table.Values)
                    {
                        if ((string)cb.SelectedItem == charac.name)
                            chardesc = charac;
                    }
                    for (int i = 1; i <= chardesc.max_degree; i++)
                    {
                        val_box.Items.Add(i);
                    }
                    break;
            }
        }
        private void chrom_changed(object sender, EventArgs e)
        {
            ComboBox cb = (ComboBox)sender;
            TextBox tb = (TextBox)table_layout.Controls[7];
            ChromosomeType chrom = null;
            ChromosomeTable chtable = (ChromosomeTable)treeView1.SelectedNode.Tag;
            foreach (ChromosomeType chromt in chtable.table)
            {
                if ((string)cb.SelectedItem == chromt.name)
                    chrom = chromt;
            }
            tb.Text = chrom.amount_locuses.ToString();
        }
        private void gene_changed(object sender, EventArgs e)
        {
            ComboBox cb = (ComboBox)sender;
            TextBox tb = (TextBox)table_layout.Controls[7];
            GeneType g = null;
            GeneTable gtable = (GeneTable) treeView1.SelectedNode.Tag;
            foreach (GeneType gg in gtable.gene_table)
            {
                if ((string)cb.SelectedItem==gg.name)
                    g=gg;
            }
            tb.Text = g.amount_alelles.ToString();
        }
        private void charac_changed(object sender, EventArgs e)
        {
            ComboBox cb = (ComboBox)sender;            
            int index = table_layout.Controls.IndexOf(cb);
            ComboBox cb2 = (ComboBox)table_layout.Controls[index + 2];
            int charac_amount=0;
            int add = 0;
            switch (treeView1.SelectedNode.Parent.Text)
            {
                case "Natural selection links":
                    charac_amount = Convert.ToInt32(table_layout.Controls[5].Text);
                    break;
                case "Reproduction links":
                    charac_amount = Convert.ToInt32(table_layout.Controls[7].Text);
                    add = 2;
                    break;
            }
            if (index != 3+add +  charac_amount* 4)
            {
                for (int i = 3; i < 7; i++)
                {
                    table_layout.Controls[index + i].Show();
                }
                for (int i = 1; i < charac_amount; i++)
                {
                    ComboBox cb1 = (ComboBox)table_layout.Controls[index + 4 * i];
                    cb1.Items.Remove(cb.SelectedItem);
                }
            }
            cb.Enabled = false;
            PhenotypeTable t = (PhenotypeTable)table_layout.Controls[3].Tag;
            for (int i = 0; i <= t.characteristic_table[cb.Text].max_degree; i++)
            {
                cb2.Items.Add(i);
            }
        }
        private void value_changed(object sender, EventArgs e)
        {
            bool b = true;
            PhenotypeTable t = (PhenotypeTable)table_layout.Controls[3].Tag;
            switch (treeView1.SelectedNode.Parent.Text)
            {
                case "Genome and phenotype links":
                    table_layout.Controls[13].Show();
                    TableLayoutPanel table = (TableLayoutPanel)table_layout.Controls[12];
                    table.Controls.Clear();
                    table.RowStyles.Clear();
                    table.ColumnStyles.Clear();
                    table.ColumnCount = 0;
                    table.RowCount = 0;
                    GenomePhenotypeLink gphlink = (GenomePhenotypeLink)treeView1.SelectedNode.Tag;
                    ComboBox charac = (ComboBox)table_layout.Controls[9];
                    ComboBox val = (ComboBox)sender;
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(File.ReadAllText(gphlink.path));
                    foreach (XmlNode node in doc.GetElementsByTagName("characteristic"))
                    {
                        if (node.Attributes[1].Value == (string)charac.SelectedItem)
                        {
                            foreach (XmlNode n in node.ChildNodes[0].ChildNodes)
                            {
                                if (n.Attributes[0].Value == val.SelectedItem.ToString())
                                {
                                    Label l = new Label();
                                    l.Text = "Gene";
                                    l.Anchor = AnchorStyles.Left;
                                    l.AutoSize = true;
                                    TextBox tb = new TextBox();
                                    tb.Text = n.ChildNodes[0].ChildNodes[0].Attributes[1].Value;
                                    tb.Enabled = false;
                                    table.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 155));
                                    table.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 180));
                                    table.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                                    table.Controls.Add(l, 0, 0);
                                    table.Controls.Add(tb, 1, 0);
                                    table.RowCount = 1;
                                    table.ColumnCount = 2;
                                    for (int i = 0; i < n.ChildNodes[0].ChildNodes[0].Attributes.Count - 3; i++)
                                    {
                                        Label l1 = new Label();
                                        l1.Text = "Allele #" + i.ToString() + " amount";
                                        l1.Anchor = AnchorStyles.Left;
                                        l1.AutoSize = true;
                                        MyNUD nud = new MyNUD();
                                        nud.Value = Convert.ToInt32(n.ChildNodes[0].ChildNodes[0].Attributes[i + 3].Value);
                                        nud.Size = new System.Drawing.Size(50, 23);
                                        table.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                                        table.Controls.Add(l1, 0, table.RowCount);
                                        table.Controls.Add(nud, 1, table.RowCount);
                                        table.RowCount++;
                                    }
                                    break;
                                }
                            }
                            break;
                        }
                    }
                    table.Enabled = false;
                    break;
                case "Reproduction links":
                    for (int i = 0; i < t.characteristics_amount; i++)
                    {
                        ComboBox cb = (ComboBox)table_layout.Controls[11 + 4 * i];
                        if (cb.SelectedItem == null)
                        {
                            b = false;
                            break;
                        }
                    }
                    if (b)
                    {
                        ReproductionLink replink = (ReproductionLink)treeView1.SelectedNode.Tag;
                        IntMassive repvector = new IntMassive(t.characteristics_amount);
                        for (int i = 0; i < Convert.ToInt32(table_layout.Controls[7].Text); i++)
                        {
                            ComboBox cb1 = (ComboBox)table_layout.Controls[9 + 4 * i];
                            ComboBox cb = (ComboBox)table_layout.Controls[11 + 4 * i];
                            int j = -1;
                            foreach (CharacteristicDescription desc in t.characteristic_table.Values)
                            {
                                j++;
                                if (desc.name == (string)cb1.SelectedItem)
                                {
                                    repvector.massive[j] = (int)cb.SelectedItem;
                                    break;
                                }
                            }
                        }
                        table_layout.Controls[8 + 4 * t.characteristics_amount].Show();
                        NumericUpDown nud = (NumericUpDown)table_layout.Controls[9 + 4 * t.characteristics_amount];
                        nud.Show();
                        try
                        {
                            nud.Value = replink.reproduction[repvector];
                            table_layout.Controls[10 + 4 * t.characteristics_amount].Show();
                        }
                        catch
                        {
                            nud.Value = 0;
                        }
                    }
                    break;
                case "Natural selection links":
                    for (int i = 0; i < t.characteristics_amount; i++)
                    {
                        ComboBox cb = (ComboBox)table_layout.Controls[9 + 4 * i];
                        if (cb.SelectedItem == null)
                        {
                            b = false;
                            break;
                        }
                    }
                    if (b)
                    {
                        NaturalSelectionLink link = (NaturalSelectionLink)treeView1.SelectedNode.Tag;
                        int[] vector = new int[t.characteristics_amount];
                        for (int i = 0; i < Convert.ToInt32(table_layout.Controls[5].Text); i++)
                        {
                            ComboBox cb1 = (ComboBox)table_layout.Controls[7 + 4 * i];
                            ComboBox cb = (ComboBox)table_layout.Controls[9 + 4 * i];
                            int j = -1;
                            foreach (CharacteristicDescription desc in t.characteristic_table.Values)
                            {
                                j++;
                                if (desc.name == (string)cb1.SelectedItem)
                                {
                                    vector[j] = (int)cb.SelectedItem;
                                    break;
                                }
                            }
                        }
                        Event ev = link.mapCharacteristicVectorIntoEventVector(vector);
                        table_layout.Controls[6 + 4 * t.characteristics_amount].Show();
                        ComboBox cb2 = (ComboBox)table_layout.Controls[7 + 4 * t.characteristics_amount];
                        cb2.Show();
                        cb2.SelectedItem = ev.event_name;
                        table_layout.Controls[8 + 4 * t.characteristics_amount].Show();
                    }
                    break;
            }
        }
        private void cbox1_select_change(object sender, EventArgs e)
        {
            ComboBox chrom_cb = (ComboBox)sender;
            ComboBox locus_cb =(ComboBox)table_layout.Controls["locus"];
            ComboBox cb = (ComboBox)table_layout.Controls["type_box"];
            ChromosomeTable chrom_t = (ChromosomeTable)table_layout.Controls[3].Tag;
            locus_cb.Items.Clear();
            locus_cb.Text = null;
            try
            {
                table_layout.Controls["prob_box"].Text = null;
            }
            catch
            {
                cb.SelectedItem = null;
            }
            foreach (ChromosomeType chrom in chrom_t.table)
            {
                if (chrom.name == (string)chrom_cb.SelectedItem)
                {                    
                    for (int i = 0; i < chrom.amount_locuses; i++)
                    {
                        locus_cb.Items.Add(i);
                    }
                }
            }
        }
        private void cbox2_select_change(object sender, EventArgs e)
        {
            ComboBox cb = (ComboBox)sender;
            ChromosomeTable chrom_t=(ChromosomeTable)table_layout.Controls[3].Tag;
            foreach (ChromosomeType chrom in chrom_t.table)
            {
                if (chrom.name == table_layout.Controls["name"].Text)
                {
                    try
                    {
                        TextBox tb = (TextBox)table_layout.Controls["prob_box"];
                        CrossingoverLink cross_link = (CrossingoverLink)cb.Tag;
                        tb.Text = cross_link.massive_probalities[chrom.id][(int)cb.SelectedItem].ToString();
                        table_layout.Controls[12].Show();
                    }
                    catch
                    {
                        ComboBox cb1 = (ComboBox)table_layout.Controls["type_box"];
                        ChromosomeGeneLink chrom_gen_link = (ChromosomeGeneLink)cb.Tag;
                        GeneTable gen_t = (GeneTable) table_layout.Controls[5].Tag;
                        foreach (GeneType g in gen_t.gene_table)
                        {
                            if (g.allele_type_id == chrom_gen_link.link[chrom.id.ToString()][(int)cb.SelectedItem])
                            {
                                cb1.SelectedItem = g.name;
                                break;
                            }
                        }
                        table_layout.Controls[14].Show();
                    }
                }
            }
        }
        private void rename_click(object sender, EventArgs e)
        {
            Button b = (Button)sender;            
            if (b.Text == "Rename")
            {
                foreach (Control c in table_layout.Controls)
                {
                    if ((c.Enabled) && (c != b))
                    {
                        ctrl_list.Add(c);
                        c.Enabled = false;
                    }
                }
                table_layout.Controls[1].Enabled = true;
                b.Text = "Save";
            }
            else
            {
                object tag = treeView1.SelectedNode.Tag;
                string name = table_layout.Controls[1].Text;
                XmlDocument doc = new XmlDocument();
                string path=null;
                if ((treeView1.SelectedNode.Level != 0)&&(treeView1.SelectedNode.Parent.Parent.Text!="Species")&&(treeView1.SelectedNode.Level<3))
                {
                    switch (treeView1.SelectedNode.Parent.Text)
                    {
                        case "Gene tables":
                            GeneTable gt = (GeneTable)tag;
                            path = gt.path;
                            gt.name = name;
                            break;
                        case "Chromosome tables":
                            ChromosomeTable chrt = (ChromosomeTable)tag;
                            path = chrt.path;
                            chrt.name = name;
                            break;
                        case "Phenotype tables":
                            PhenotypeTable phent = (PhenotypeTable)tag;
                            path = phent.path;
                            phent.name = name;
                            break;
                        case "Natural selection tables":
                            NaturalSelectionTable natselt = (NaturalSelectionTable)tag;
                            path = natselt.path;
                            natselt.name = name;
                            break;
                        case "Species":
                            Species sp = (Species)tag;
                            path = sp.path;
                            sp.name = name;
                            break;
                        case "Chromosome and gene links":
                            ChromosomeGeneLink chrom_gen_link = (ChromosomeGeneLink)tag;
                            chrom_gen_link.name = name;
                            path = chrom_gen_link.path;
                            break;
                        case "Genome and phenotype links":
                            GenomePhenotypeLink gen_phen_link = (GenomePhenotypeLink)tag;
                            path = gen_phen_link.path;
                            gen_phen_link.name = name;
                            break;
                        case "Natural selection links":
                            NaturalSelectionLink natsel_link = (NaturalSelectionLink)tag;
                            path = natsel_link.path;
                            natsel_link.name = name;
                            break;
                        case "Crossingover links":
                            CrossingoverLink cross_link = (CrossingoverLink)tag;
                            path = cross_link.path;
                            cross_link.name = name;
                            break;
                        case "Reproduction links":
                            ReproductionLink rep_link = (ReproductionLink)tag;
                            path = rep_link.path;
                            rep_link.name = name;
                            break;
                    }
                }
                else
                {
                    switch (treeView1.SelectedNode.Level)
                    {
                        case 0:
                            path = model.model_path;
                            model.model_name = name;
                            break;
                        case 3:
                            Population pop = (Population)tag;
                            path = pop.path;
                            pop.name = name;
                            break;
                        case 4:
                            Individual indi = (Individual)tag;
                            path = indi.path;
                            indi.name = name;
                            break;
                    }
                }
                doc.LoadXml(File.ReadAllText(path));
                doc.DocumentElement.SetAttribute("Name",table_layout.Controls[1].Text);
                doc.Save(path);
                foreach (Control c in ctrl_list)
                {
                    c.Enabled = true;
                }
                ctrl_list.Clear();
                table_layout.Controls[1].Enabled = false;
                b.Text = "Rename";
                treeView1.SelectedNode.Text = name;
            }

        }
        private List<Control> ctrl_list = new List<Control>();
        private void change_click(object sender, EventArgs e)
        {
            Button b = (Button)sender;
            if (b.Text == "Change")
            {
                foreach (Control c in table_layout.Controls)
                {
                    if ((c.Enabled) && (c != b))
                    {
                        ctrl_list.Add(c);
                        c.Enabled = false;
                    }
                }
                table_layout.GetControlFromPosition(1, table_layout.GetPositionFromControl(b).Row).Enabled = true;
                b.Text = "Save";
            }
            else
            {
                if (treeView1.SelectedNode.Level == 7)
                {
                    XmlDocument doc = new XmlDocument();
                    ComboBox cb = (ComboBox)table_layout.Controls[3];
                    Individual indi = (Individual)treeView1.SelectedNode.Parent.Parent.Parent.Tag;
                    doc.LoadXml(File.ReadAllText(indi.path));
                    ChromosomeType chromcat = (ChromosomeType)treeView1.SelectedNode.Parent.Tag;
                    foreach (XmlNode node in doc.GetElementsByTagName("chromosome_pair"))
                    {
                        if (node.Attributes[0].Value == chromcat.id.ToString())
                        {
                            XmlNode n = node.ChildNodes[treeView1.SelectedNode.Parent.Index - treeView1.SelectedNode.Parent.Parent.FirstNode.Index];
                            string[] str = n.ChildNodes[0].InnerText.Split(' ');
                            str[treeView1.SelectedNode.Parent.FirstNode.Index - treeView1.SelectedNode.Index] = cb.SelectedItem.ToString();
                            n.ChildNodes[0].InnerText = null;
                            for (int i = 0; i < str.Count(); i++)
                            {
                                n.ChildNodes[0].InnerText += str[i];
                                if (i != str.Count() - 1)
                                    n.ChildNodes[0].InnerText += " ";
                            }
                        }
                    }
                    doc.Save(indi.path);
                    model_update();
                    indi.massive_chromosomes[chromcat.id.ToString()][treeView1.SelectedNode.Parent.Index - treeView1.SelectedNode.Parent.Parent.FirstNode.Index].massive_locus[treeView1.SelectedNode.Parent.FirstNode.Index - treeView1.SelectedNode.Index].gene.allele = (int)cb.SelectedItem;
                }
                else
                {
                    string path = null;
                    object tag = treeView1.SelectedNode.Tag;
                    MyXmlDocument doc = new MyXmlDocument();
                    ChromosomeTable t;
                    ChromosomeType ch = null;
                    switch (treeView1.SelectedNode.Parent.Text)
                    {
                        case "Genome and phenotype links":
                            GenomePhenotypeLink genphlink = (GenomePhenotypeLink)tag;
                            path = genphlink.path;
                            doc.LoadXml(File.ReadAllText(path));
                            TableLayoutPanel table = (TableLayoutPanel)table_layout.Controls[12];
                            ComboBox charac = (ComboBox)table_layout.Controls[9];
                            ComboBox val = (ComboBox)table_layout.Controls[11];
                            foreach (XmlNode node in doc.GetElementsByTagName("characteristic"))
                            {
                                if (node.Attributes[1].Value == (string)charac.SelectedItem)
                                {
                                    foreach (XmlNode n in node.ChildNodes[0].ChildNodes)
                                    {
                                        if (n.Attributes[0].Value == val.SelectedItem.ToString())
                                        {
                                            for (int i = 0; i < table.RowCount - 1; i++)
                                            {
                                                MyNUD nud1 = (MyNUD)table.Controls[3 + i * 2];
                                                n.ChildNodes[0].ChildNodes[0].Attributes[i + 3].Value = nud1.Value.ToString();
                                                if (nud1.IsIncremented())
                                                    doc.Increment(n.ChildNodes[0].ChildNodes[0].Attributes[2], nud1.difference);
                                                if(nud1.IsDecremented())
                                                    doc.Decrement(n.ChildNodes[0].ChildNodes[0].Attributes[2], nud1.difference);
                                            }
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                            doc.Save(path);
                            break;
                        case "Reproduction links":
                            ReproductionLink replink = (ReproductionLink)tag;
                            path = replink.path;
                            doc.LoadXml(File.ReadAllText(path));
                            NumericUpDown nud = (NumericUpDown)table_layout.GetControlFromPosition(1, table_layout.GetPositionFromControl(b).Row);
                            nud.Enabled = true;
                            if (nud.Value == 0)
                            {
                                MessageBox.Show("Number of children must not be 0!");
                                nud.Value = 1;
                                return;
                            }
                            PhenotypeTable reppht = (PhenotypeTable)table_layout.Controls[3].Tag;
                            string[] repvector = new string[reppht.characteristics_amount];
                            for (int i = 0; i < Convert.ToInt32(table_layout.Controls[7].Text); i++)
                            {
                                ComboBox char_cb = (ComboBox)table_layout.Controls[9 + 4 * i];
                                ComboBox val_cb = (ComboBox)table_layout.Controls[11 + 4 * i];
                                int j = -1;
                                foreach (CharacteristicDescription desc in reppht.characteristic_table.Values)
                                {
                                    j++;
                                    if (desc.name == (string)char_cb.SelectedItem)
                                    {
                                        repvector[j] = val_cb.SelectedItem.ToString();
                                        break;
                                    }
                                }
                            }
                            string repstr_vector = null;
                            for (int i = 0; i < repvector.Count(); i++)
                            {
                                repstr_vector += " " + repvector[i];
                                if (i == repvector.Count() - 1)
                                    repstr_vector += ";";
                            }
                            foreach (XmlNode node in doc.GetElementsByTagName("characteristic_sets"))
                            {
                                if (node.InnerText.Contains(repstr_vector))
                                {
                                    node.InnerText = node.InnerText.Replace(repstr_vector, null);
                                    bool ev_ex = false;
                                    foreach (XmlNode n in doc.GetElementsByTagName("reproduction_event"))
                                    {
                                        if (n.Attributes[2].Value == nud.Value.ToString())
                                        {
                                            n.ChildNodes[0].InnerText += repstr_vector;
                                            ev_ex = true;
                                            break;
                                        }
                                    }
                                    if (!ev_ex)
                                    {
                                        XmlElement el = doc.CreateElement("reproduction_event");
                                        el.SetAttribute("Id", Functions.set_id(replink).ToString());
                                        el.SetAttribute("Name", "Having " + nud.Value.ToString() + " children");
                                        el.SetAttribute("ChildrenAmount", nud.Value.ToString());
                                        XmlElement el1 = doc.CreateElement("characteristic_sets");
                                        el1.InnerText = repstr_vector;
                                        el.AppendChild(el1);
                                        doc.DocumentElement.AppendChild(el);
                                        doc.Increment(doc.DocumentElement.Attributes[5]);
                                    }
                                    break;
                                }
                            }
                            doc.Save(path);
                            break;
                        case "Natural selection links":
                            NaturalSelectionLink link = (NaturalSelectionLink)tag;
                            path = link.path;
                            doc.LoadXml(File.ReadAllText(path));
                            ComboBox cb5 = (ComboBox)table_layout.GetControlFromPosition(1, table_layout.GetPositionFromControl(b).Row);
                            PhenotypeTable pht = (PhenotypeTable)table_layout.Controls[3].Tag;
                            string[] vector = new string[pht.characteristics_amount];
                            for (int i = 0; i < Convert.ToInt32(table_layout.Controls[5].Text); i++)
                            {
                                ComboBox char_cb = (ComboBox)table_layout.Controls[7 + 4 * i];
                                ComboBox val_cb = (ComboBox)table_layout.Controls[9 + 4 * i];
                                int j = -1;
                                foreach (CharacteristicDescription desc in pht.characteristic_table.Values)
                                {
                                    j++;
                                    if (desc.name == (string)char_cb.SelectedItem)
                                    {
                                        vector[j] = val_cb.SelectedItem.ToString();
                                        break;
                                    }
                                }
                            }
                            string str_vector = null;
                            for (int i = 0; i < vector.Count(); i++)
                            {
                                str_vector += " " + vector[i];
                                if (i == vector.Count() - 1)
                                    str_vector += ";";
                            }
                            foreach (XmlNode node in doc.GetElementsByTagName("characteristic_sets"))
                            {
                                if (node.InnerText.Contains(str_vector))
                                {
                                    foreach (XmlNode n in doc.GetElementsByTagName("event"))
                                    {
                                        if ((n.Attributes[1].Value == (string)cb5.SelectedItem) && (n.ChildNodes[0] != node))
                                        {
                                            node.InnerText = node.InnerText.Replace(str_vector, null);
                                            n.ChildNodes[0].InnerText += str_vector;
                                            if (n.Attributes[0].Value == "1")
                                            {
                                                foreach (ReproductionLink reprlink in model.model_reproduction_links.Values)
                                                {
                                                    if (reprlink.path_to_natsel_link == path)
                                                    {
                                                        XmlDocument doc1 = new XmlDocument();
                                                        doc1.LoadXml(System.IO.File.ReadAllText(reprlink.path));
                                                        foreach (XmlNode n1 in doc1.GetElementsByTagName("characteristic_sets"))
                                                        {
                                                            if (n1.InnerText.Contains(str_vector))
                                                            {
                                                                n1.InnerText = n1.InnerText.Replace(str_vector, null);
                                                                break;
                                                            }
                                                        }
                                                        doc1.Save(reprlink.path);
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                foreach (ReproductionLink reprlink in model.model_reproduction_links.Values)
                                                {
                                                    if (reprlink.path_to_natsel_link == link.path)
                                                    {
                                                        bool ev_ex = false;
                                                        MyXmlDocument doc1 = new MyXmlDocument();
                                                        doc1.LoadXml(System.IO.File.ReadAllText(reprlink.path));
                                                        foreach (XmlNode n1 in doc1.GetElementsByTagName("reproduction_event"))
                                                        {
                                                            if (n1.Attributes[2].Value == "2")
                                                            {
                                                                ev_ex = true;
                                                                n1.InnerText += str_vector;
                                                                break;
                                                            }
                                                        }
                                                        if (!ev_ex)
                                                        {
                                                            XmlElement el = doc.CreateElement("reproduction_event");
                                                            el.SetAttribute("Id", Functions.set_id(reprlink).ToString());
                                                            el.SetAttribute("Name", "Having 2 children");
                                                            el.SetAttribute("ChildrenAmount", "2");
                                                            XmlElement el1 = doc.CreateElement("characteristic_sets");
                                                            el1.InnerText = str_vector;
                                                            el.AppendChild(el1);
                                                            doc1.DocumentElement.AppendChild(el);
                                                            doc1.Increment(doc1.DocumentElement.Attributes[5]);
                                                        }
                                                        doc1.Save(reprlink.path);
                                                    }
                                                }
                                            }
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                            doc.Save(path);
                            break;
                        case "Chromosome and gene links":
                            t = (ChromosomeTable)table_layout.Controls[3].Tag;
                            ChromosomeGeneLink link1 = (ChromosomeGeneLink)tag;
                            path = link1.path;
                            doc.LoadXml(System.IO.File.ReadAllText(path));
                            ComboBox cb = (ComboBox)table_layout.GetControlFromPosition(1, 4);
                            foreach (ChromosomeType c in t.table)
                            {
                                if (c.name == (string)cb.SelectedItem)
                                {
                                    ch = c;
                                    break;
                                }
                            }
                            ComboBox cb1 = (ComboBox)table_layout.GetControlFromPosition(1, 5);
                            GeneType g = null;
                            GeneTable gt = (GeneTable)table_layout.GetControlFromPosition(1, 2).Tag;
                            ComboBox cb2 = (ComboBox)table_layout.GetControlFromPosition(1, 6);
                            foreach (GeneType gg in gt.gene_table)
                            {
                                if ((string)cb2.SelectedItem == gg.name)
                                {
                                    g = gg;
                                    break;
                                }
                            }
                            foreach (XmlNode node in doc.GetElementsByTagName("chromosome"))
                            {
                                if (node.Attributes[0].Value == ch.id.ToString())
                                {
                                    string[] str = node.ChildNodes[0].InnerText.Split(' ');
                                    str[(int)cb1.SelectedItem] = g.allele_type_id.ToString();
                                    node.ChildNodes[0].InnerText = null;
                                    for (int i = 0; i < str.Count(); i++)
                                    {
                                        node.ChildNodes[0].InnerText += str[i];
                                        if (i != str.Count() - 1)
                                            node.ChildNodes[0].InnerText += " ";
                                    }
                                }
                                break;
                            }
                            doc.Save(path);
                            break;
                        case "Crossingover links":
                            t = (ChromosomeTable)table_layout.Controls[3].Tag;
                            TextBox tb = (TextBox)table_layout.GetControlFromPosition(1, 5);
                            if ((Convert.ToDouble(tb.Text) <= 100) && (Convert.ToDouble(tb.Text) >= 0))
                            {
                                CrossingoverLink link2 = (CrossingoverLink)tag;
                                path = link2.path;
                                doc.LoadXml(System.IO.File.ReadAllText(path));
                                ComboBox cb3 = (ComboBox)table_layout.GetControlFromPosition(1, 3);
                                foreach (ChromosomeType c in t.table)
                                {
                                    if (c.name == (string)cb3.SelectedItem)
                                    {
                                        ch = c;
                                        break;
                                    }
                                }
                                ComboBox cb4 = (ComboBox)table_layout.GetControlFromPosition(1, 4);
                                foreach (XmlNode node in doc.GetElementsByTagName("chromosome"))
                                {
                                    if (node.Attributes[0].Value == ch.id.ToString())
                                    {
                                        string[] str = node.ChildNodes[0].InnerText.Split(' ');
                                        str[(int)cb4.SelectedItem] = tb.Text;
                                        node.ChildNodes[0].InnerText = null;
                                        for (int i = 0; i < str.Count(); i++)
                                        {
                                            node.ChildNodes[0].InnerText += str[i];
                                            if (i != str.Count() - 1)
                                                node.ChildNodes[0].InnerText += " ";
                                        }
                                    }
                                    break;
                                }
                                doc.Save(path);
                            }
                            break;
                    }
                    model_update();
                    switch (treeView1.SelectedNode.Parent.Text)
                    {
                        case "Chromosome and gene links":
                            treeView1.SelectedNode.Tag = model.model_chromosome_gene_links[path];
                            break;
                        case "Genome and phenotype links":
                            treeView1.SelectedNode.Tag = model.model_genome_phenotype_links[path];
                            break;
                        case "Natural selection links":
                            treeView1.SelectedNode.Tag = model.model_natural_selection_links[path];
                            break;
                        case "Crossingover links":
                            treeView1.SelectedNode.Tag = model.model_crossingover_links[path];
                            break;
                        case "Reproduction links":
                            treeView1.SelectedNode.Tag = model.model_reproduction_links[path];
                            break;
                    }
                }
                foreach (Control c in ctrl_list)
                {
                    c.Enabled = true;
                }
                ctrl_list.Clear();
                table_layout.GetControlFromPosition(1, table_layout.GetPositionFromControl(b).Row).Enabled = false;
                b.Text = "Change";
            }
        }
        public class PropControls
        {
            private bool b = false;
            private bool bb = false;
            public List<Label> labels = new List<Label>();
            public List<TextBox> boxes = new List<TextBox>();
            private int count;
            Label l1 = new Label();
            Label l2 = new Label();
            Label l3 = new Label();
            public ComboBox cbox1 = new ComboBox();
            public ComboBox cbox2 = new ComboBox();
            public TextBox tbox = new TextBox();
            public ComboBox cbox3 = new ComboBox();
            public PropControls(int i)
            {
                count = i;
                for (int k = 0; k < i; k++)
                {
                    labels.Add(new Label());
                    labels[k].Anchor = AnchorStyles.Left;
                    labels[k].AutoSize = true;
                    boxes.Add(new TextBox());
                    boxes[k].Enabled = false;
                    boxes[k].Size = new Size(188, 23);
                }
            }
            public PropControls(string str)
            {
                l1.Anchor = AnchorStyles.Left;
                l2.Anchor = AnchorStyles.Left;
                l3.Anchor = AnchorStyles.Left;
                l1.AutoSize = true;
                l2.AutoSize = true;
                l3.AutoSize = true;
                l1.Text = "Chromosome's name";
                l2.Text = "Locus";
                cbox1.Name = "name";
                cbox2.Name = "locus";
                b = true;
                switch (str)
                {
                    case "crossingover":
                        count = 3;
                        l3.Text = "Probability";
                        tbox.Name = "prob_box";
                        tbox.Enabled = false;
                        tbox.KeyPress += new KeyPressEventHandler(Functions.textBox_KeyPress);
                        tbox.Size = new Size(35, 23);
                        break;
                    case "chrom_gene":
                        count = 4;
                        l3.Text = "Gene";
                        cbox3.Name = "type_box";
                        cbox3.Enabled = false;
                            bb=true;
                        break;
                }    
                for (int k = 0; k < count; k++)
                {
                    labels.Add(new Label());
                    labels[k].Anchor = AnchorStyles.Left;
                    labels[k].AutoSize = true;
                    boxes.Add(new TextBox());
                    boxes[k].Enabled = false;
                    boxes[k].Size = new Size(188, 23);
                }
            }
            public void add_to_table_layout_panel(TableLayoutPanel table)
            {                
                for (int i = 0; i < count; i++)
                {                    
                    table.Controls.Add(labels[i], 0, i );
                    table.Controls.Add(boxes[i], 1, i);
                        table.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                        table.RowCount++;
                }
                if (b)
                {
                    table.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                    table.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                    table.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                    table.Controls.Add(l1, 0, count);
                    table.Controls.Add(l2, 0, count + 1);
                    table.Controls.Add(l3, 0, count + 2);
                    table.Controls.Add(cbox1, 1, count);
                    table.Controls.Add(cbox2, 1, count + 1);
                    if (bb)
                        table.Controls.Add(cbox3, 1, count + 2);
                    else
                        table.Controls.Add(tbox, 1, count + 2);
                    table.RowCount += 3;
                }
            }
        }

        private void MainWindow_Load(object sender, EventArgs e)
        {   
            treeView1.Size = new Size(this.Width / 3, this.Height * 90 / 100);
            table_layout.Location = new Point(treeView1.Width + 10, treeView1.Location.Y);
        }

        private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (model != null)
            {
                GraphicWindow gr_win = new GraphicWindow(model);
                gr_win.ShowDialog();
            }
        }

        private void phenotypeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewPhenotypeTable new_phen_table = new NewPhenotypeTable(model);
            new_phen_table.ShowDialog(this);
            model_update();
        }

        private void naturalSelectionToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            NewNatSelTable new_natsel_table = new NewNatSelTable(model);
            new_natsel_table.ShowDialog(this);
            model_update();
        }

        private void genomeAndPhenotypeToolStripMenuItem_Click(object sender, EventArgs e)
        {
           NewGenPhenLink new_gen_phen_link = new NewGenPhenLink(model);
            new_gen_phen_link.ShowDialog(this);
            model_update();
        }

        private void naturalSelectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewNatSelLink new_natsel_link = new NewNatSelLink(model);
            new_natsel_link.ShowDialog(this);
            model_update();
        }

        private void edit_butt_Click(object sender, EventArgs e)
        {
            object tag = treeView1.SelectedNode.Tag;
            switch(treeView1.SelectedNode.Parent.Text)
            {
                case "Gene tables":
                    GeneTable gt = (GeneTable)tag;
                    GeneTableEdit gen_edit = new GeneTableEdit(model,gt);
                    gen_edit.ShowDialog(this);
                    treeView1.SelectedNode.Tag = new GeneTable(gt.path);
                    break;
                case "Chromosome tables":
                    ChromosomeTable chrt = (ChromosomeTable)tag;
                    ChromosomeTableEdit chrom_edit = new ChromosomeTableEdit(model, chrt);
                    chrom_edit.ShowDialog(this);
                    treeView1.SelectedNode.Tag = new ChromosomeTable(chrt.path);
                    break;
                case "Phenotype tables":
                    PhenotypeTable phent = (PhenotypeTable)tag;
                    PhenotypeTableEdit phen_edit = new PhenotypeTableEdit(model, phent);
                    phen_edit.ShowDialog(this);
                    treeView1.SelectedNode.Tag = new PhenotypeTable(phent.path);
                    break;
                case "Natural selection tables":
                    NaturalSelectionTable natselt = (NaturalSelectionTable)tag;
                    NatSelTableEdit natsel_edit = new NatSelTableEdit(model, natselt);
                    natsel_edit.ShowDialog(this);
                    treeView1.SelectedNode.Tag = new NaturalSelectionTable(natselt.path);
                    break;
            }
            model_update();
        }

        private void reproductionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewReprodLink link = new NewReprodLink(model);
            link.ShowDialog(this);
            model_update();
        }

        private void specieToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewSpecie sp = new NewSpecie(model);
            sp.ShowDialog(this);
            model_update();
        }

        private void chromosomeAndGeneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewChromGeneLink link = new NewChromGeneLink(model);
            link.ShowDialog(this);
            model_update();
        }

        private void crossingoverToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            NewCrossLink link = new NewCrossLink(model);
            link.ShowDialog(this);
            model_update();
        }

        private void addToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            switch (contextMenuStrip3.Items[0].Text)
            {
                case "Add new reproduction link":
                    NewReprodLink repl = new NewReprodLink(model);
                    repl.ShowDialog(this);
                    break;
                case "Add new natural selection link":
                    NewNatSelLink natl = new NewNatSelLink(model);
                    natl.ShowDialog(this);
                    break;
                case "Add new chromosome and gene link":
                    NewChromGeneLink chrl = new NewChromGeneLink(model);
                    chrl.ShowDialog(this);
                    break;
                case "Add new genome and phenotype link":
                    NewGenPhenLink gphl = new NewGenPhenLink(model);
                    gphl.ShowDialog(this);
                    break;
                case "Add new crossingover link":
                    NewCrossLink crl = new NewCrossLink(model);
                    crl.ShowDialog(this);
                    break;
                case "Add new gene table":
                   NewGeneTable gt = new NewGeneTable(model);
                    gt.ShowDialog(this);
                    break;
                case "Add new chromosome table":
                    NewChromosomeTable cht= new NewChromosomeTable(model);
                    cht.ShowDialog(this);
                    break;
                case "Add new phenotype table":
                    NewPhenotypeTable pht= new NewPhenotypeTable(model);
                    pht.ShowDialog(this);
                    break;
                case "Add new natural selection table":
                    NewNatSelTable natt= new NewNatSelTable(model);
                    natt.ShowDialog(this);
                    break;
                case "Add new specie":
                    NewSpecie sp= new NewSpecie(model);
                    sp.ShowDialog(this);
                    break;
                case "Add new population":
                    NewPop pop = new NewPop(model,(Species)treeView1.SelectedNode.Tag);
                    pop.ShowDialog(this);
                    break;
                case "Add new individual":
                    NewIndi ind = new NewIndi(model,(Population)treeView1.SelectedNode.Tag);
                    ind.ShowDialog(this);
                    break;
            }
            model_update();
        }
        
    }    
}